import 'package:dailoz/constants.dart';
import 'package:dailoz/data/loading_data.dart';
import 'package:dailoz/entity/user_entity.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/service/user_service/user_service.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/input_utils.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/utils/validate.dart';
import 'package:dailoz/view_model/user.dart';
import 'package:dailoz/views/home.dart';
import 'package:dailoz/views/login.dart';
import 'package:dailoz/widgets/bottom_login_signup_text_button.dart';
import 'package:dailoz/widgets/button_widget.dart';
import 'package:dailoz/widgets/input_field.dart';
import 'package:dailoz/widgets/progress_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SignUp extends StatefulWidget {
  const SignUp({Key? key}) : super(key: key);

  static String id = 'signup_view';

  @override
  State<SignUp> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  TextEditingController? phoneNumController;
  TextEditingController? passwordController;
  TextEditingController? validatePassController;
  TextEditingController? userNameController;

  FocusNode? phoneNumFocusNode;
  FocusNode? passwordFocusNode;
  FocusNode? validatePassFocusNode;
  FocusNode? userNameFocusNode;

  IconData? passwordVisibleIcon = Icons.visibility_off_outlined;

  bool passwordInvisible = true;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    phoneNumController = TextEditingController();
    passwordController = TextEditingController();
    validatePassController = TextEditingController();
    userNameController = TextEditingController();
    userNameFocusNode = FocusNode();
    passwordFocusNode = FocusNode();
    validatePassFocusNode = FocusNode();
    phoneNumFocusNode = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    phoneNumController?.dispose();
    passwordController?.dispose();
    validatePassController?.dispose();
    userNameController?.dispose();
    InputUtil.clear();
  }

  void _signup(WebSocketData? provider) async {
    setState(() {
      isLoading = !isLoading;
    });
    String? userName = userNameController?.text;
    String? phoneNum = phoneNumController?.text;
    String? password = passwordController?.text;
    String? validatePass = validatePassController?.text;
    if (!Validate.validateUserName(userName!)) {
      userNameController?.clear();
      userNameFocusNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    }
    if (!Validate.validatePhoneNumber(phoneNum!)) {
      phoneNumController?.clear();
      phoneNumFocusNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      showToast(S.of(context).validatePhoneNum);
      return;
    } else if (!Validate.validatePassword(password!)) {
      passwordController?.clear();
      passwordFocusNode?.requestFocus();
      validatePassController?.clear();
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (!Validate.validatePassword(validatePass!)) {
      if (validatePass != password) {
        validatePassController?.clear();
        validatePassFocusNode?.requestFocus();
      }
      setState(() {
        isLoading = !isLoading;
      });
      return;
    } else if (validatePass != password) {
      validatePassController?.clear();
      validatePassFocusNode?.requestFocus();
      setState(() {
        isLoading = !isLoading;
      });
      showToast(S.of(context).secondPass);
      return;
    } else {
      final userInfo = User(userName: userName, password: password);
      userInfo.phoneNum = int.parse(phoneNum);
      dynamic response = await UserService.signUp(userInfo);
      if (response != null) {
        if (!mounted) return;
        ResponseJsonEntity responseJsonEntity =
            ResponseJsonEntity.fromJson(response);
        UserEntity userEntity = UserEntity.fromJson(responseJsonEntity.data);
        User user =
            User(phoneNum: userEntity.phoneNum, password: userEntity.password);
        // UserService.loginOperation(context, response, provider!);
        bool flag = await UserService.login(user);
        if (flag) {
          if (!mounted) return;
          Navigator.of(context).pushNamedAndRemoveUntil(
              Home.id, (Route<dynamic> route) => false);
        } else {
          print(flag);
        }
      }
    }
    setState(() {
      isLoading = !isLoading;
    });
  }

  // void sendCode() {
  //   showToast(S.of(context).validateCodeSuccess);
  // }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<WebSocketData>(context);
    return ProgressWidget(
      loading: isLoading,
      msg: S.of(context).isSignUp,
      child: GestureDetector(
        onTap: () {
          phoneNumFocusNode!.unfocus();
          userNameFocusNode!.unfocus();
          passwordFocusNode!.unfocus();
          validatePassFocusNode!.unfocus();
        },
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: Center(
            child: SizedBox(
              width: SizeConfig.getProportionateScreenWidth(327.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(60.0),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        S.of(context).signUpButtonText,
                        style: TextStyle(
                          color: buttonWidgetColor,
                          fontSize: SizeConfig.getProportionateFontSize(36.0),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(52.0),
                  ),
                  InputField(
                    controller: userNameController,
                    onSubmitted: (newValue) {
                      newValue.trim().isNotEmpty
                          ? null
                          : showToast(S.of(context).usernameNotNull);
                    },
                    keyboardType: TextInputType.text,
                    borderColor: inputBorderColor,
                    borderWidth: 1.0,
                    hintText: S.of(context).userName,
                    prefixIcon: Icons.account_circle_outlined,
                    prefixIconColor: inputIconColor,
                    prefixIconSize: SizeConfig.getProportionateFontSize(23.0),
                    hintTextColor: inputHintTextColor,
                    hintTextSize: 16.0,
                    focusNode: userNameFocusNode,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(15.0),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      InputField(
                        focusNode: passwordFocusNode,
                        controller: passwordController,
                        keyboardType: TextInputType.text,
                        borderColor: inputBorderColor,
                        borderWidth: 1.0,
                        hintText: S.of(context).password,
                        textInvisible: passwordInvisible,
                        hintTextColor: inputHintTextColor,
                        prefixIcon: Icons.lock_outline,
                        prefixIconColor: inputIconColor,
                        prefixIconSize:
                            SizeConfig.getProportionateFontSize(22.0),
                        suffixIcon: passwordVisibleIcon,
                        suffixIconColor: inputIconColor,
                        suffixIconSize:
                            SizeConfig.getProportionateFontSize(16.0),
                        suffixOnPress: () {
                          setState(() {
                            passwordInvisible = !passwordInvisible;
                            if (passwordVisibleIcon ==
                                Icons.visibility_off_outlined) {
                              passwordVisibleIcon = Icons.visibility_outlined;
                            } else {
                              passwordVisibleIcon =
                                  Icons.visibility_off_outlined;
                            }
                          });
                        },
                        hintTextSize: 16.0,
                      ),
                      SizedBox(
                        height: SizeConfig.getProportionateScreenHeight(5.0),
                      ),
                      Container(
                        padding: EdgeInsets.only(
                          left: SizeConfig.getProportionateScreenWidth(12.0),
                        ),
                        width: SizeConfig.getProportionateScreenWidth(310.0),
                        child: Text(
                          S.of(context).passwordText,
                          style: TextStyle(
                            color: const Color(0xffC0C4CC),
                            fontSize: SizeConfig.getProportionateFontSize(14.0),
                          ),
                        ),
                      ),
                    ],
                  ),
                  InputField(
                    focusNode: validatePassFocusNode,
                    controller: validatePassController,
                    keyboardType: TextInputType.text,
                    borderColor: inputBorderColor,
                    borderWidth: 1.0,
                    hintText: S.of(context).password,
                    textInvisible: passwordInvisible,
                    hintTextColor: inputHintTextColor,
                    prefixIcon: Icons.lock_outline,
                    prefixIconColor: inputIconColor,
                    prefixIconSize: SizeConfig.getProportionateFontSize(22.0),
                    suffixIcon: passwordVisibleIcon,
                    suffixIconColor: inputIconColor,
                    suffixIconSize: SizeConfig.getProportionateFontSize(16.0),
                    suffixOnPress: () {
                      setState(() {
                        passwordInvisible = !passwordInvisible;
                        if (passwordVisibleIcon ==
                            Icons.visibility_off_outlined) {
                          passwordVisibleIcon = Icons.visibility_outlined;
                        } else {
                          passwordVisibleIcon = Icons.visibility_off_outlined;
                        }
                      });
                    },
                    hintTextSize: 16.0,
                    onSubmitted: (newValue) {
                      if (newValue != passwordController?.text) {
                        showToast(S.of(context).secondPass);
                      }
                    },
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(10.0),
                  ),
                  InputField(
                    controller: phoneNumController,
                    onSubmitted: (newValue) {
                      newValue.trim().isNotEmpty
                          ? null
                          : showToast(S.of(context).phoneNotNull);
                    },
                    keyboardType: TextInputType.phone,
                    borderColor: inputBorderColor,
                    borderWidth: 1.0,
                    hintText: S.of(context).phoneNum,
                    prefixIcon: Icons.phone_outlined,
                    prefixIconColor: inputIconColor,
                    prefixIconSize: SizeConfig.getProportionateFontSize(22.0),
                    hintTextColor: inputHintTextColor,
                    hintTextSize: 16.0,
                    focusNode: phoneNumFocusNode,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(15.0),
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(30.0),
                  ),
                  ButtonWidget(
                    width: 320.0,
                    height: 52.0,
                    buttonText: S.of(context).signUpButtonText,
                    onPressed: () async {
                      InputUtil.throttle("tag", () {
                        _signup(provider);
                      });
                    },
                    buttonColor: buttonWidgetColor,
                    buttonTextColor: Colors.white,
                  ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(30.0),
                  ),
                  // const LoginSignUpDivider(),
                  // SizedBox(
                  //   height: SizeConfig.getProportionateScreenHeight(20.0),
                  // ),
                  // Row(
                  //   mainAxisAlignment: MainAxisAlignment.center,
                  //   children: <Widget>[
                  //     ThirdPartyLoginButton(
                  //       onPressed: () {},
                  //       icon: Icons.facebook,
                  //       iconColor: buttonWidgetColor,
                  //     ),
                  //     SizedBox(
                  //       width: SizeConfig.getProportionateScreenWidth(16.0),
                  //     ),
                  //     ThirdPartyLoginButton(
                  //       onPressed: () {
                  //         showToast(
                  //             "click meclick meclick meclickclick meclick me meclick me");
                  //       },
                  //       icon: Icons.wechat,
                  //       iconColor: Colors.green,
                  //     ),
                  //   ],
                  // ),
                  SizedBox(
                    height: SizeConfig.getProportionateScreenHeight(20.0),
                  ),
                  BottomLoginSignUpTextButton(
                    text: S.of(context).haveAccount,
                    buttonText: S.of(context).loginButtonText,
                    onPressed: () {
                      Navigator.pushReplacementNamed(context, Login.id);
                    },
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
